<?php defined('BASEPATH') OR exit('No direct script access allowed');

class my_facebook{
	private $CI;
	private $status = true;
	private $app_id;
	private $app_secret;
	// private $redirect_url = "";
	// private $permissions = 'manage_pages,publish_stream,offline_access';
	// offline_access,user_photos,publish_stream,user_hometown,user_about_me,email,read_friendlists
	
	private $fb_id_pelimaniaco;
	private $access_token_user;
	private $access_token_page;
	
	
	function my_facebook(){
		$this->CI =& get_instance();
		
		$this->app_id 				= Sys::$facebook_app_id;
		$this->app_secret 			= Sys::$facebook_app_secret;
		$this->access_token_user	= Sys::$facebook_access_token_user;
		$this->access_token_page	= Sys::$facebook_access_token_page;
		$this->fb_id_pelimaniaco	= Sys::$facebook_id_pelimaniaco;
	}
	
	
	/**
	 * SERVICIOS QUE PERMITEN PUBLICAR LAS COSAS EN FACEBOOK
	 * Se autentifica en facebook
	 * @param string $redirect_url
	 */
	protected function authFacebook($redirect_url){
		if(empty($_REQUEST['code'])) {
	        $dialog_url ="http://www.facebook.com/dsialog/oauth?client_id=".$this->app_id."&redirect_uri=".urlencode($redirect_url)."&scope=".$this->permissions;
			// echo $dialog_url;exit;
			header("Location: ".$dialog_url);
			exit;
	    }
	    return true;
	}
	
	/**
	 * Obtiene un accessToken de facebook
	 * @param string $redirect_url
	 */
	protected function getToken($redirect_url, $trim=false){
		$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$this->app_id."&redirect_uri=".
			 				$redirect_url."&client_secret=".$this->app_secret."&code=".self::$params['code'];
        $access_token = file_get_contents($token_url);
        
        if($trim)
        	$access_token = explode("&", str_replace("access_token=", "", $access_token));
        
		return $access_token;
	}
	
	/**
	 * Publica un Post en facebook
	 * 
	 * @param string $type					Tipo 'films' o 'series'
	 * @param int $id						Id Pelicula o Capitulo
	 * 
	 * @return int 
	 */
	public function _makePost($type, $id){
			
			// $url_encode			= urlencode(Sys::$url_base.'services/facebook/post.json?type='.$type.'&id='.$id);
			// $is_authFacebook	= $this->authFacebook($url_encode);
			
			$field = ($type=='films') 
									? 
										array('table' => 'peliculas', 'field_where' => 'id_pelicula') 
									: 
										array('table' => 'series_capitulos', 'field_where' => 'id_capitulo') 
									;
			
			if(!$this->update_field_id_facebook($field['table'], $id, $field['field_where'], '', FALSE)){
				
				$model	= (  $type=='films') ? 'films_model' : 'series_model';
				$method	= ( $model=='films_model') ? 'getInfoFilm' : 'getEpisode';
				$id		= ($method=='getInfoFilm') ? array('id_film'=>$id) : array('episode'=>$id);
				
				$this->CI->load->model($model);
				$data = $this->CI->{$model}->{$method}($id);
				$fb_data = $this->{'build_array_'.$type}($data);
				
				// $access_token	= $this->getToken($url_encode);
				// $graph_url		= "https://graph.facebook.com/me?" . $access_token;
				// $usr_info		= json_decode(file_get_contents($graph_url));
	
				//	EN CASO DE QUE EL ACCESS TOKEN DE LA PAGINA CADUQUE OBTIENE UNO NUEVO (DESCOMENTAR ESTAS LINEAS SI ES EL CASO)
				// $page_url			= "https://graph.facebook.com/".$this->$fb_id_pelimaniaco."?fields=access_token&access_token=".$this->$access_token_user;
				// $page_access_token	= json_decode(file_get_contents($page_url));
	
				$url	= "https://graph.facebook.com/".$this->fb_id_pelimaniaco."/feed";
				
				$data = array(
							'access_token'	=> $this->access_token_page,//$page_access_token['access_token']
							'message'		=> $fb_data['message'],
							'link'			=> $fb_data['link'],
							'picture'		=> $fb_data['picture'],
							'name'			=> $fb_data['name'],
							'caption'		=> $fb_data['caption'],
							'description'	=> $fb_data['description'],
							'properties'	=> $fb_data['properties'],
							'actions'		=> json_encode (array('name'=>'Ver más Peliculas Online :D', 'link'=>'http://www.pelimaniaco.com'))
						);
				
				 $res= $this->curlExec($url,$data);
				 
				 if($type=='films')
					$this->update_field_id_facebook('peliculas', $id['id_film'], 'id_pelicula', $res->id);
				 else
				 	$this->update_field_id_facebook('series_capitulos', $id['episode'], 'id_capitulo', $res->id);
				 
				 return '$res->id';
			 }
	}


	private function update_field_id_facebook($table, $id_table, $field_where, $id_fb, $update = TRUE){
		$this->CI->db->select('id_facebook')->from($table)->where($field_where,$id_table);
		$res	= $this->CI->db->get();
		$res	= $res->row_array();
		
		$exist_id_fb = ($res['id_facebook']==NULL) ? FALSE : TRUE;
		
		if($update && !$exist_id_fb){
			$this->CI->db->where($field_where,$id_table);
			$this->CI->db->update($table,array('id_facebook' => $id_fb));
		}else if (!$update) return $exist_id_fb;
		
	}


	/**
	 * CONSTRUYE EL ARRAY CON LOS DATOS DE LA PELICULA QUE SE PUBLICARA EN FB
	 * 
	 * @param array $data			Datos de la Pelicula
	 * @return array
	 */
	private function build_array_films($data){
		$array = array();
		$str_genres	= "";
		$str_source	= "";
		$str_scr	= "";
		$str_cast	= "";
		
		$year		= substr($data[0]['date_release'],0,4);
		$synopsis	= (is_null($data[0]['synopsis_spa'])) ? $data[0]['synopsis_eng'] : $data[0]['synopsis_spa'];
		
		if(isset($data[0]['categories']))
			foreach ($data[0]['categories'] as $gen)
				$str_genres .= $gen['name']."-";
		
		if(isset($data[0]['screenshots']))
			foreach ($data[0]['screenshots'] as $scr)
				if($scr['primary']==1){$str_scr = $scr['url']; break;}
			
		if(isset($data[0]['sources']))
			foreach ($data[0]['sources'] as $source)
				$str_source .= $source['name']." & ";
				
		if(isset($data[0]['cast']))
			foreach ($data[0]['cast'] as $cast)
				$str_cast .= $cast['name'].",";
		
		$array['message'] 	= "Publicada Pelicula ".$data[0]['title']." ($year) | $str_genres \n\nCapturas: $str_scr \n\n";
		$array['message'] 	.= "Formato	| ".$data[0]['format_film']." \n";
		$array['message'] 	.= "Calidad	| ".$data[0]['quality']." \n";
		$array['message'] 	.= "Duración | ".$data[0]['duration']." \n";
		$array['message'] 	.= "Servidores de descarga | $str_source \n";
		$array['message'] 	.= "Tamaño	| ".$data[0]['size']." \n";
		$array['message'] 	.= "Idioma	| ".$data[0]['language']." con Subtitulos en ".$data[0]['subtitle']."";
						
		$array['link']		= Sys::$url_base.'films~'.$data[0]['id_film'].'~'.$data[0]['clean_title'];
		$array['picture'] 	= $data[0]['posters'][0]['big'];
		$array['name']		= "Ver Online ".$data[0]['title']." ($year)";
		$array['caption']	= "Actores: $str_cast";
		$array['description']	= $synopsis;
		$array['properties']	= "[{'text': 'Ver mas...','href': 'http://www.pelimaniaco.com'}]";	
		
		return $array;
		
	}

	/**
	 * CONSTRUYE EL ARRAY CON LOS DATOS DEL EPISODIO QUE SE PUBLICARA EN FB
	 * 
	 * @param array $data			Datos del Episodio
	 * @return array
	 */
	private function build_array_series($data){
		$data = array($data);
		$array = array();
		$str_genres	= "";
		$str_source	= "";
		$str_scr	= "";
		$str_cast	= "";
		
		$synopsis	= (is_null($data[0]['synopsis_spa'])) ? $data[0]['synopsis_eng'] : $data[0]['synopsis_spa'];
		
		if(isset($data[0]['categories']))
			foreach ($data[0]['categories'] as $gen)
				$str_genres .= $gen['name']."-";
		
		if(isset($data[0]['screenshots']))
			foreach ($data[0]['screenshots'] as $scr)
				if($scr['primary']==1){$str_scr = $scr['url_screen']; break;}
			
		if(isset($data[0]['sources']))
			foreach ($data[0]['sources'] as $source)
				$str_source .= $source['name']." & ";
				
		if(isset($data[0]['cast']))
			foreach ($data[0]['cast'] as $cast)
				$str_cast .= $cast['name'].",";
		
		if($data[0]['no_season']==1 && $data[0]['no_episode'])
			$str_msg = "Estreno Serie ".$data[0]['title_serie']." | Temporada ".$data[0]['no_season']."\n Publicado Capitulo ".$data[0]['no_episode']." - ".$data[0]['title_episode'];
		else if ($data[0]['no_season']>1 && $data[0]['no_episode']==1)
			$str_msg = "Estreno Temporada ".$data[0]['no_season']."\n Publicado Capitulo ".$data[0]['no_episode']." - ".$data[0]['title_episode'];
		else if ($data[0]['no_season']>1 && $data[0]['no_episode']>1)
			$str_msg = "Publicado Capitulo ".$data[0]['no_episode']." - ".$data[0]['title_episode'];
			
		$array['message'] 	= "$str_msg | $str_genres \n\nCapturas: $str_scr \n\n";
		$array['message'] 	.= "Serie	| ".$data[0]['title_serie']." \n";
		$array['message'] 	.= "Temporada | ".$data[0]['no_season']." \n";
		$array['message'] 	.= "Formato	| ".$data[0]['format_episode']." \n";
		$array['message'] 	.= "Calidad	| ".$data[0]['quality']." \n";
		$array['message'] 	.= "Duración | ".$data[0]['duration']." \n";
		$array['message'] 	.= "Servidores de descarga | $str_source \n";
		$array['message'] 	.= "Tamaño	| ".$data[0]['size']." \n";
		$array['message'] 	.= "Idioma	| ".$data[0]['language']." con Subtitulos en ".$data[0]['subtitle'];
						
		$array['link']		= Sys::$url_base.'series~'.$data[0]['id_episode'].'~'.$data[0]['clean_title_serie'].'~'.$data[0]['clean_title_episode'];
		$array['picture'] 	= $data[0]['url_poster_big'];
		$array['name']		= "Ver Online Capitulo ".$data[0]['no_episode']." - ".$data[0]['title_episode']." | Temporada ".$data[0]['no_season'];
		$array['caption']	= "Actores: $str_cast";
		$array['description'] = $synopsis;
		$array['properties']	= "[{'text': 'Ver Serie ".$data[0]['title_serie']."','href': ".Sys::$url_base.$data[0]['id_season']."-".$data[0]['clean_title_serie']."}]"; 
		
		return $array;
	}

	
	public function comment($comment=0, $user_id=0, $action='add'){
		$res_usr = $this->CI->db->query("SELECT * FROM users WHERE id = ".$user_id);
		if($res_usr->num_rows() > 0){
			$data_usr = $res_usr->row();
			$access_token = str_replace('access_token=', '', $data_usr->token_facebook);
			
			if($action == 'delete'){
				$res = $this->CI->db->query("SELECT facebook_id FROM ".$comment['table']." WHERE id = ".$comment['comment_id']);
				if($res->num_rows() > 0){
					$data = $res->row();
					if($data->facebook_id){
						try{
							$graph_url = 'https://graph.facebook.com/'.$data->facebook_id.'?method=delete&'.$data_usr->token_facebook;
							$res = @file_get_contents($graph_url);
						}catch(Exception $e){}
					}
				}
			}else{
				//obtenemos los datos del comentario
				$res = $this->CI->db->query("SELECT co.id AS comment_id, c.comment, co.facebook_id 
				FROM comments AS c INNER JOIN ".$comment['table']." AS co ON c.id = co.comment_id 
				WHERE co.enable = 1 AND c.id = ".$comment['comment_id']." 
					AND co.".$comment['field']." = ".$comment[($comment['key_param']!=''? $comment['key_param']: $comment['field'])]);
				
				if($res->num_rows() > 0){
					$data = $res->row();
					
					//obtenemos los datos del objeto
					$res_post = $this->CI->db->query("SELECT facebook_id FROM ".$comment['table2']." 
							WHERE id = ".$comment[($comment['key_param']!=''? $comment['key_param']: $comment['field'])]);
					if($res_post->num_rows() > 0){
						$data_post = $res_post->row();
						if($action == 'add'){
							$graph_url = 'https://graph.facebook.com/'.$data_post->facebook_id.'/comments';
							
							// ARRAY CON Los datos del comentario
							$data_comment = array(
								'access_token' 	=> $access_token, 		// ACCESS TOKEN PARA PERMISOS
								'message' 		=> $data->comment
							);
							
							$res = $this->curlExec($graph_url, $data_comment);
							if(isset($res->id))
								$this->CI->db->query("UPDATE ".$comment['table']." SET facebook_id = '".$res->id."' 
														WHERE comment_id = ".$comment['comment_id']);
						}
					}
				}
			}
		}
	}
	
	public function like($comment=0, $user_id=0, $action='add'){
		if($comment['table'] == 'brands' || $comment['table'] == 'store')
			return true;
		
		$res_usr = $this->CI->db->query("SELECT * FROM users WHERE id = ".$user_id);
		if($res_usr->num_rows() > 0){
			$data_usr = $res_usr->row();
			$access_token = str_replace('access_token=', '', $data_usr->token_facebook);
			
			//obtenemos los datos del obj del like
			$res = $this->CI->db->query("SELECT facebook_id  FROM ".$comment['table']." 
			WHERE id = ".$comment[($comment['key_param']!=''? $comment['key_param']: $comment['field'])]);
			
			if($res->num_rows() > 0){
				$data = $res->row();
				
				if($action == 'add'){
					$graph_url = 'https://graph.facebook.com/'.$data->facebook_id.'/likes';
					$data_like = array(
						'access_token' 	=> $access_token
					);
					$res = $this->curlExec($graph_url, $data_like);
				}elseif($action == 'delete'){
					if($data->facebook_id){
						try{
							$graph_url = 'https://graph.facebook.com/'.$data->facebook_id.'/likes?method=delete&'.$data_usr->token_facebook;	
							$res = @file_get_contents($graph_url);
						}catch(Exception $e){}
					}
				}
			}
		}
	}
	
	/**
	 * Publica un item en facebook
	 * @param entero $item_id
	 */
	public function item($item_id=0, $user_id=0, $action='add'){
		$res_usr = $this->CI->db->query("SELECT token_facebook, fb_album_item_id FROM users WHERE id = ".$user_id);
		if($res_usr->num_rows() > 0){
			$data_usr = $res_usr->row();
			$access_token = str_replace('access_token=', '', $data_usr->token_facebook);
			
			//obtenemos los datos del item
			$res = $this->CI->db->query("SELECT i.id, i.label, b.name AS brand, sl.name AS store, img.file_name, i.facebook_id 
				FROM items AS i INNER JOIN items_imgs as ii ON i.id = ii.item_id 
					INNER JOIN images AS img ON img.id = ii.image_id LEFT JOIN brands AS b ON b.id = i.brand_id 
					LEFT JOIN store_locations AS sl ON sl.id = i.bought_in 
				WHERE i.id = ".$item_id." LIMIT 1");
			
			if($res->num_rows() > 0){
				$data = $res->row();
				
				if($action == 'add'){
					//si no tiene creado el album lo crea
					if($data_usr->fb_album_item_id == NULL){
						$data_usr->fb_album_item_id = $this->createAlbum("fb_album_item_id", $user_id, $access_token);
					}
					
					$graph_url = 'https://graph.facebook.com/'.$data_usr->fb_album_item_id.'/photos';
					
					//Preparamos la imagen para enviarla a fb
					$urlImagen = UploadFile::pathBig().$data->file_name; //UploadFile::urlBig().$data->file_name;
					$imagenTmp = tempnam('.', 'xhttp-tmp-'); // CREA UNA RUTA TEMPORAL PARA LA IMAGEN
					file_put_contents($imagenTmp, file_get_contents($urlImagen)); //crea la imagen temporal
					$img = '@'.$imagenTmp;
					
					Sys::loadLanguage(Sys::$idioma_load);
					$message = $data->label;
					if($data->brand != '' && $data->brand != NULL)
						$message .= ", ".lang('txt_brand').": ".$data->brand;
					if($data->brand != '' && $data->brand != NULL)
						$message .= ", ".lang('txt_store').": ".$data->store;
					
					// ARRAY CON LA INFORMACION DEL postyle QUE SE ENVIARA A FB
					$data_foto = array(
						'access_token' 	=> $access_token, 		// ACCESS TOKEN PARA PERMISOS
						'message' 		=> $message,
						'source' 		=> $img
					);
					
					$res = $this->curlExec($graph_url, $data_foto);
					if(isset($res->id))
						$this->CI->db->query("UPDATE items SET facebook_id = '".$res->id."' WHERE id = ".$item_id);
					
					unlink(str_replace('@', '', $img)); //eliminamos la imagen temporal
					
				}elseif($action == 'delete'){
					if($data->facebook_id){
						try{
							$graph_url = 'https://graph.facebook.com/'.$data->facebook_id.'?method=delete&'.$data_usr->token_facebook;
							$res = @file_get_contents($graph_url);
						}catch(Exception $e){}
					}
				}
			}
		}
	}
	
	
	private function curlExec($graph_url, $data){
		$handle = curl_init($graph_url);
		curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($handle, CURLOPT_POST, true);
		curl_setopt($handle, CURLOPT_HTTPHEADER, array('Expect:'));
		curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
		
		$respuesta = json_decode(curl_exec($handle)); // OBTIENE EL RESULTADO DEL ENVIO DE DATOS DEL EVENTO
		
		curl_close($handle);
		
		return $respuesta;
	}
}